$import("com.joypard.platform.organization.post.PostView");
$import("com.joypard.platform.organization.org.OrgView");

/**
 * 选择上级岗位组件
 */
K.def("com.joypard.platform.organization.post.SelectParentPostComponent", {
	statics : {
		/**
		 * 创建左边组织树
		 */
		createOrgTree : function() {
			return OrgView.createOrgTreePanel({
				width : "40%",
				region : "west",
				margins : "2 0 1 2"
			});
		},
		/**
		 * 创建右边岗位列表,双击选择
		 */
		createPostGrid : function(config, btns) {
			var options = {
				title : "岗位列表",
				iconCls : "frame_paenl_102",
				frame : true,
				region : "center",
				margins : "2 2 0 2",
				buttons : btns,
				sm : new Ext.grid.RowSelectionModel({
					singleSelect : true
				}),
				store : PostView.createPostsByOrgCodeStore(),
				columns : [ {
					header : "岗位编码",
					dataIndex : "cusCode"
				}, {
					header : "岗位名称",
					dataIndex : "name"
				}, {
					header : "站岗人员",
					dataIndex : "users",
					renderer : function(value) {
						return value ? K.arrayToStr(value, "account") : "";
					}
				} ],
				buttons : btns
			};
			K.extend(options, config);
			return new K.Ext.grid.GridPanel(options);
		},
		/**
		 * 选择上级岗位组件
		 */
		createSelectParentPostWindow : function(config) {
			var orgTree = this.createOrgTree();
			var postGrid = this.createPostGrid({}, [ {
				text : '确定',
				handler : function() {
					var record = postGrid.getSelectionModel().getSelected();
					if (record) {
						postGrid.fireEvent("rowclick", postGrid, postGrid.getStore().indexOf(record));
					} else {
						K.err("请选择一个上级岗位");
					}
				}
			}, {
				text : '取消',
				handler : function() {
					wind.hide();
				}
			} ]);

			var onSelect = K.createInterceptor(config.onSelect, function(grid, rowIndex) {
				var record = grid.getStore().getAt(rowIndex);
				if (false !== config.onSelect(record)) {
					wind.hide();
				}
				return false;
			});

			if (config.onSelect) {
				postGrid.on("rowclick", onSelect);
			}

			if (!config.height) {
				config.height = Ext.getBody().getHeight();
			}

			if (!config.width) {
				config.width = Ext.getBody().getWidth();
			}

			orgTree.on("click", function(orgNode) {
				postGrid.getStore().load({
					params : {
						orgId : orgNode.id
					}
				});
			});

			var root = orgTree.getRootNode();
			root.on("expand", function(root) {
				if (!root.firstClicked) {
					root.firstChild.fireEvent("click", root.firstChild);
					root.firstClicked = true;
				}
			});
			orgTree.on("afterrender", function() {
				root.expand();
			});

			var options = {
				title : "选择上级岗位",
				layout : "border",
				closeAction : "hide",
				items : [ orgTree, postGrid ]
			};
			K.extend(options, config);

			var wind = new K.Ext.Window(options);
			return wind;
		}
	}
});
